<template>
  <div class="user-profile">
    <!-- 导航栏 -->
    <van-nav-bar
      class="app-nav-bar"
      left-arrow
      title="个人信息"
      @click-left="$router.back()"
    ></van-nav-bar>
    <!-- /导航栏 -->
    
    <input type="file" hidden accept="image/*" ref="file" @change="onFileChange">

    <van-cell title="头像" is-link center @click="$refs.file.click()">
      <van-image
        width="30"
        height="30"
        round
        fit="cover"
        :src="user.photo"
      />
    </van-cell>
    <van-cell title="昵称" is-link :value="user.name" @click="isEditNameShow = true"></van-cell>
    <van-cell title="性别" is-link :value="user.gender === 0 ? '男' : '女'"></van-cell>
    <van-cell title="生日" is-link :value="user.birthday === '' ? '保密' : user.birthday"></van-cell>

    <van-popup 
      v-model="isEditNameShow" 
      position="bottom" 
      :style="{ height: '100%' }" 
    >
      <!-- $event获取监听事件的参数 -->
      <!-- 当你传递给子组件的数据既要使用又要修改，例如这里的name
          这种情况下我们可以使用v-model简写 -->
      <!-- 原代码： :name="user.name" @update-name="user.name=$event" -->
      <!-- v-model="user.name" 
            默认传递给子组件一个名字叫value的数据
            :value="user.name"
            默认监听input事件
            @input="user.name=$event"
          v-model的本质还是父子组件通信，它仅仅是简化了父组件的使用
      -->
      <update-name v-model="user.name" @close="isEditNameShow = false"/>
    </van-popup>

    <van-popup 
      class="update-photo-popup"
      v-model="isEditPhotoShow" 
      position="bottom" 
      :style="{ height: '100%' }" 
    >
      <update-photo 
        v-if="isEditPhotoShow"
        :file="previewImage" 
        @close="isEditPhotoShow = false"
        @update-photo="user.photo=$event"
      />
    </van-popup>
  </div>
</template>

<script>
import {getUserProfile} from '@/api/user'
import UpdateName from './components/update-name'
import UpdatePhoto from './components/update-photo'
export default {
  name: 'UserProfile',
  components: {
    UpdateName,UpdatePhoto
  },
  props: {},
  data () {
    return {
      user:{},//用户数据
      isEditNameShow: false,//编辑昵称的显示状态
      isEditPhotoShow: false,//编辑图片的显示状态
      previewImage: null, //上传预览图片
    }
  },
  computed: {},
  watch: {},
  created () {
    this.loadUserProfile()
  },
  mounted () {},
  methods: {
    async loadUserProfile () {
      const {data} = await getUserProfile()
      console.log(data);
      this.user = data.data
    },
    onFileChange () {
      //展示弹出层
      this.isEditPhotoShow = true
      //在弹出层里面预览图片
      const file = this.$refs.file.files[0]
      // const blob = window.URL.createObjectURL(this.$refs.file.files[0])
      //console.log(this.$refs.file.files[0]);
      // console.log(blob)
      this.previewImage = file
      //为了解决相同文件不触发change时间，所以在这里手动的清空file的value
      this.$refs.file.value = ''
    }
  }
}
</script>

<style scoped lang="less">
.van-popup {
  background-color: #f5f7f9;
}
.update-photo-popup {
  background-color: #000;
}
</style>